class_name CastSkillSys
extends System

var CATCH_READ = ["FrameTime", "Ext", "SkillCmdC", "SkillLibC", "DelaySkillsC"]
var catch_read: Array

var dirty := []


func _init():
	system_name = "CastSkillSys"
	listen_modify("on_cmd", "SkillCmdC", [])


func _system_ready():
	catch_read = world.query_manager.fetch_components(CATCH_READ)


func _system_process(_delta):
	if not dirty.size():
		return
	var read = catch_read
	var frame = read[0].data as FrameTime
	var ext = read[1].data as Ext
	var cmd_m = read[2]
	var lib_m = read[3]
	var delay_m = read[4]

	var SkillAttrKey = C.SkillAttrKey
	for fighter in dirty:
		var cmd_c = cmd_m.get(fighter) as SkillCmdC
		if not cmd_c:
			continue
		#check alive
		if not ext.is_alive(fighter):
			continue

		var sc = lib_m.get(fighter) as SkillLibC
		var dc = delay_m.get(fighter) as DelaySkillsC

		for cmd in cmd_c.arr:
			var skill = sc.map.get(cmd.skill_id)
			if not skill:
				continue
			var targets = ext.skill_select(skill, fighter, cmd)
			if not targets || targets.size() == 0:
				continue
			var skill_delay =  skill.get(SkillAttrKey.castPreDelay)
			var delay = skill_delay if skill_delay else 0
			# change use_skill DelayCastSkillSystem will handle cast skill
			dc.use_skill = DelaySkillsC.UseSkill.new(
				skill, targets, frame.count + (delay / frame.frame_interval | 0)
			)
		cmd_c.arr.clear()
	dirty.clear()


#@listenModify(Multi<SkillCmdC>)
func on_cmd(e, _read):
	dirty.append(e.id)
